package com.sofwin.controller;

import com.github.pagehelper.PageInfo;
import com.sofwin.Constants;
import com.sofwin.pojo.SRole;
import com.sofwin.service.SRoleService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("system/role")
public class RoleController {
    @Autowired
    private SRoleService roleService;

    @RequestMapping("data")
    @RequiresRoles("2") // 只能此角色id[副经理]可以访问
    public String data(SRole role, @RequestParam(required = true,defaultValue = "1")Integer pageNum,
                       @RequestParam(required = true,defaultValue = "3") Integer pageSize, Model model){
        PageInfo<SRole> pageInfo = roleService.selectRoleByPage(role,pageNum,pageSize);
        model.addAttribute("page",pageInfo);
        model.addAttribute("data",pageInfo.getList());
        model.addAttribute("role",role);
        return "role/data";
    }

    @RequestMapping("deletes")
    @ResponseBody
    public Map delete(Integer[] ids){
        boolean status = roleService.deleteRoles(ids);
        Map map = new HashMap();
        map.put("status",status);
        return map;
    }

    @RequestMapping("toEdit")
    public String toEdit(Integer id,Model model){
        if (id != null){
            // 编辑
            SRole role = roleService.selectById(id);
            model.addAttribute("role",role);
        }
        return "role/edit";
    }

    @RequestMapping("save")
    @ResponseBody
    public Map save(SRole role){
        boolean status = roleService.insertRole(role);
        Map map = new HashMap();
        map.put("status",status);
        return map;
    }

    @RequestMapping("getPermission")
    public String getPermission(Integer roleId,Model model){
        model.addAttribute("roleId",roleId);
        return "role/permission";
    }

    /*@PostMapping("editPermission1")
    @ResponseBody
    public Map editPermission1(boolean isChecked,Integer roleId,Integer resourceId){
        Map map = new HashMap();
        boolean status = roleService.savePermission(isChecked,roleId,resourceId);
        map.put("status",status);
        return map;
    }*/
    @GetMapping("editPermission")
    @ResponseBody
    public Map editPermission(Integer roleId,Integer[] resourceIds){
        Map map = new HashMap();
        boolean status = roleService.savePermission1(roleId,resourceIds);
        map.put("status",status);
        return map;
    }

}
